package aliai

import (
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	sts20150401 "github.com/alibabacloud-go/sts-20150401/v2/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"github.com/emirpasic/gods/maps/treemap"
	"time"
)

var (
	clients *treemap.Map = treemap.NewWithStringComparator() //k:accId.bucketName
)

// Access Key ID（访问密钥ID）
// Access Key Secret（访问密钥Secret）
// Endpoint：默认sts.cn-qingdao.aliyuncs.com，更多查看https://api.aliyun.com/product/Sts
type Client struct {
	AccId    string
	AccSec   string
	EndPoint string

	//安全令牌客户端
	stsClient *sts20150401.Client
	stsTokens *treemap.Map //k:roleArn v:*StsToken
}

// AssumeRole - 获取扮演角色的临时身份凭证
// https://help.aliyun.com/zh/ram/developer-reference/api-sts-2015-04-01-assumerole?spm=a2c4g.11186623.0.0.5fa3908bneIpWU
// roleArn:要扮演的RAM角色ARN，eg. acs:ram::1992037670454548:role/sts123
func (this *Client) AssumeRoleStsGet(roleArn string) (token *StsToken, err error) {

	if v, ok := this.stsTokens.Get(roleArn); ok {
		token = v.(*StsToken)
		if !token.IsExpired() {
			return token, nil
		}
	}

	expireSnds := int64(3600)
	assumeRoleRequest := &sts20150401.AssumeRoleRequest{
		DurationSeconds: tea.Int64(expireSnds),
		RoleArn:         tea.String(roleArn),
		RoleSessionName: tea.String("alice"),
	}
	runtime := &util.RuntimeOptions{}
	var result *sts20150401.AssumeRoleResponse
	result, err = this.stsClient.AssumeRoleWithOptions(assumeRoleRequest, runtime)
	if err != nil {
		return
	}
	//resp = &AssumeRoleStsGetResp{
	//	result: result,
	//}
	//if !resp.IsSuccess() {
	//	return nil,errors.New()
	//}
	//hlog.Debug(resp)
	token = &StsToken{Body: result.Body, ExpireTime: time.Now().Unix() + expireSnds}
	this.stsTokens.Put(roleArn, token)
	return
}

//商品分类识别

func NewClient(accId, accSec string, endPoint ...string) (client *Client, err error) {
	client = &Client{}
	client.AccId = accId
	client.AccSec = accSec
	config := &openapi.Config{
		AccessKeyId:     tea.String(client.AccId),
		AccessKeySecret: tea.String(client.AccSec),
	}
	if len(endPoint) > 0 {
		client.EndPoint = endPoint[0]
	} else {
		client.EndPoint = "sts.cn-qingdao.aliyuncs.com"
	}
	// Endpoint 请参考 https://api.aliyun.com/product/Sts
	config.Endpoint = tea.String(client.EndPoint)
	client.stsClient, err = sts20150401.NewClient(config)
	if err != nil {
		return nil, err
	}
	client.stsTokens = treemap.NewWithStringComparator()
	clients.Put(accId, client)
	return
}

// accId不传，默认获取第一个
func ClientInst(accId ...string) *Client {

	if clients.Size() == 0 {
		panic("该阿里云ai客户端未初始化01")
	}

	if len(accId) > 0 {
		if v, ok := clients.Get(accId[0]); !ok {
			panic("该阿里云ai客户端未初始化02")
		} else {
			return v.(*Client)
		}
	} else {
		_, v := clients.Min()
		return v.(*Client)
	}
}
